package com.app.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.app.mapper.AmmunitionMapper;
import com.app.mapper.DayWorkMapper;
import com.app.mapper.PersonTrainMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.AmmunitionVo;
import com.app.vo.CategoryVo;
import com.app.vo.DayWorkVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

@RestController
@Controller
@RequestMapping("/api/ammunition")
public class WorkshopController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DayWorkMapper dayWorkMapper;
    @Autowired
    private AmmunitionMapper ammunitionMapper;
    @Autowired
    private AmmunitionService ammunitionService;

    @GetMapping("/getDropList")//下拉框查询
    public Result<Object> getDropList(
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        CategoryVo vo = new CategoryVo();
        List<CategoryModel> categoryModelList = categoryService.getCategoryByPid(140);
        vo.setTrainDescList(categoryModelList);
        return Result.success(vo);
    }

    //添加和编辑每日工作
    @PostMapping("/insertAndUpdateDayWork")
    public Result<Object> insertAndUpdateDayWork(@RequestBody DayWorkModel dayWorkModel) {
        if (dayWorkModel.getId() > 0) {
            dayWorkModel.setUpdateTime(CommonHelp.getNowTimestamp());
            dayWorkMapper.updateById(dayWorkModel);
        } else {
            dayWorkModel.setCreateTime(CommonHelp.getNowTimestamp());
            dayWorkMapper.insert(dayWorkModel);
        }
        return Result.success("操作成功");
    }

    //查看厂房每日工作列表
    //厂房列表
    @GetMapping("/getDayWorkshopList")
    public Result<Object> getDayWorkshopList(Integer page, Integer limit) {
        Page<DayWorkModel> page1 = new Page<>();
        page1.setCurrent(page);
        page1.setSize(limit);
        QueryWrapper<DayWorkModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time").orderByDesc("id");
        Page<DayWorkModel> dayWorkModelPage = dayWorkMapper.selectPage(page1, queryWrapper);
        DayWorkVo vo = new DayWorkVo();
        vo.setList(dayWorkModelPage.getRecords());
        vo.setCount((int) dayWorkModelPage.getTotal());
        return Result.success(vo);
    }

    //删除厂房
    @GetMapping("/deleteWorkshop")
    public Result<Object> deleteWorkshop() {
        return null;
    }

    //厂房列表
    @GetMapping("/getWorkshopList")
    public Result<Object> getWorkshopList() {
        return null;
    }

    //添加和编辑弹药存储
    @PostMapping("/insertAndUpdateAmmunition")
    public Result<Object> insertAndUpdateAmmunition(@RequestBody AmmunitionModel ammunitionModel) {
        if (ammunitionModel.getWorkTimeList() != null && !ammunitionModel.getWorkTimeList().isEmpty()) {
            ammunitionModel.setWorkTime(JSON.toJSONString(ammunitionModel.getWorkTimeList()));
        }else {
            ammunitionModel.setWorkTime("[]");
        }
        try {
            if (ammunitionModel.getId() > 0) {
                ammunitionModel.setUpdateTime(CommonHelp.getNowTimestamp());
                ammunitionMapper.updateById(ammunitionModel);
            } else {
                ammunitionModel.setCreateTime(CommonHelp.getNowTimestamp());
                ammunitionMapper.insert(ammunitionModel);
            }
        } catch (Exception e) {
            return Result.success(e);
        }
        return Result.success("操作成功");
    }

    //查看厂房弹药列表
    @GetMapping("/getAmmunitionList")
    public Result<Object> getAmmunitionList(Integer page, Integer limit, String type, String department,Integer sortType) {
        Page<AmmunitionModel> page1 = new Page<>();
        page1.setCurrent(page);
        page1.setSize(limit);
        QueryWrapper<AmmunitionModel> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(type)) {
            queryWrapper.like("type", type);
        }
        if (StrUtil.isNotBlank(department)) {
            queryWrapper.like("department", department);
        }
        if (sortType==null || sortType==1){
            queryWrapper.orderByAsc("number").orderByDesc("create_time");
        }else {
            queryWrapper.orderByDesc("number").orderByDesc("create_time");
        }
        Page<AmmunitionModel> ammunitionModelPage = ammunitionMapper.selectPage(page1, queryWrapper);
        for (int i = 0; i < ammunitionModelPage.getRecords().size(); i++) {
            List<String> workList = JSONUtil.toList(ammunitionModelPage.getRecords().get(i).getWorkTime(),String.class);
//            List<String> workList = JSON.parseObject(ammunitionModelPage.getRecords().get(i).getWorkTime(), new TypeReference<List<String>>() {
//            });
            StringBuilder stringBuilder = new StringBuilder();
            if (CollectionUtil.isNotEmpty(workList)) {
                for (String string : workList) {
                    stringBuilder.append(string).append("-");
                }
                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                ammunitionModelPage.getRecords().get(i).setWorkTime(stringBuilder.toString());
            }else {
                ammunitionModelPage.getRecords().get(i).setWorkTime(null);
            }
        }
        AmmunitionVo vo = new AmmunitionVo();
        vo.setList(ammunitionModelPage.getRecords());
        vo.setCount((int) ammunitionModelPage.getTotal());
        return Result.success(vo);
    }

    //删除
    @GetMapping("/deleteAmmunition")
    public Result<Object> deleteMilitarySportsList(Integer id) {
        try {
            ammunitionMapper.deleteById(id);
        } catch (Exception e) {
            return Result.success(e);
        }
        return Result.success("操作成功");
    }

    //批量删除弹药
    @DeleteMapping("/deleteAmmunitionBatchByIds")
    public Result<Object> deleteAmmunitionBatchByIds(String ids) {
        return ammunitionService.deleteAmmunitionBatchByIds(ids);
    }

    //通过id查
    @GetMapping("/selectAmmunitionById")
    public Result<Object> selectMilitarySportsById(Integer id) {
        try {
            AmmunitionModel ammunitionModel = ammunitionMapper.selectById(id);
            List<String> workList = JSON.parseObject(ammunitionModel.getWorkTime(), new TypeReference<List<String>>() {
            });
            ammunitionModel.setWorkTimeList(workList);
            return Result.success(ammunitionModel);
        } catch (Exception e) {
            return Result.success(e);
        }
    }
}
